<template>
  <div id="annualBonusDetail">
    <p><span>{{query.year}}年</span></p>
    <div class="pageHead">
      <div class="pageLf">
        <div class="block">
          <el-select v-model="params.departmentid" placeholder="选择部门"  clearable>
            <el-option v-for="item in sDepartment" :key="item.departmentid" :label="item.departmentName" :value="item.departmentid">
            </el-option>
          </el-select>
        </div>
        <div class="block">
          <el-input v-model="params.noORname" placeholder="人员、工号"></el-input>
        </div>
        <div class="block">
          <el-button type="primary" @click="onserch" :loading='loading'>查询</el-button>
        </div>
        <div class="block">
          <el-popover placement="bottom" :width="400" trigger="click">
            <div class="pagegroup" style="padding:20px 20px 20px 20px">
              <div class="lfTitle" style="display:flex; line-height:50px;">
                <p style="width:80px;text-align:right;">岗位：</p>
                <el-input v-model="params.postname" type="text" clearable></el-input>
              </div>
              <div class="lfTitle" style="display:flex; line-height:50px;">
                <p style="width:100px; text-align:right;">员工类型：</p>
                <el-select v-model="params.registertype" class="full-width-input" clearable>
                  <el-option v-for="item in mployeetype" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </div>
            </div>
            <template #reference>
              <el-button type="text">更多</el-button>
            </template>
          </el-popover>
        </div>
      </div>
      <div class="pageRg">
        <div class="block">
          <el-button @click="cloneUser">引入人员</el-button>
        </div>
        <div class="block">
          <el-button @click="onBulkchanges">批量修改</el-button>
        </div>
        <div class="block">
          <el-button @click="onsaveAdd" :loading='loading1'>保存</el-button>
        </div>
        <div class="blocks">
          <el-dropdown>
            <el-button style="margin-left:0.5vw;">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item><span @click="isDiaor=true">导入</span></el-dropdown-item>
              <el-dropdown-item>
                <span @click="exportget">导出</span>
              </el-dropdown-item>
              <el-dropdown-item><span @click="ondelList">删除</span></el-dropdown-item>
              <el-dropdown-item><span @click="onprint">
                  打印
                </span></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
    </div>
    <div class="pageBox">
      <div class="tableContens">
        <el-table :data="tableData" height="100%" class="pageInnerTable" :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }" ref="multipleTable" @selection-change="handleSelectionChange" border>
          <el-table-column type="selection" width="55" label="姓名"></el-table-column>
          <el-table-column label="姓名" prop="name"></el-table-column>
          <el-table-column prop="jobno" label="工号" width="180">
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" width="180">
          </el-table-column>
          <el-table-column prop="postname" label="岗位">
          </el-table-column>
          <el-table-column label="年终奖">
            <template #header>
                <span><i class="el-icon-edit"></i>年终奖</span>
              </template >
            
            <template slot-scope="scope">
              <span v-if="scope.row.active">
                <el-input v-model="scope.row.annualBonus" oninput="value=value.replace(/[^0-9.]/g,'')" maxLength='9' @blur='onblurtive(scope.row)' @change="onchangeput(scope.row)"></el-input>
              </span>
              <div  v-else @click="onHidden(scope.row,'active')" style="cursor: pointer;">
                <span style="display-in"> {{scope.row.annualBonus?scope.row.annualBonus:0}}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="应纳税额">
            <template #default="{row}">
              <span>{{row.taxPayable}}</span>
            </template>
          </el-table-column>
          <el-table-column label="实发年终奖">
            <template #default="{ row}">
              <span>{{row.sfAnnualBonus}}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注">
                <template #header>
                <span><i class="el-icon-edit"></i>备注</span>
              </template >
            <template slot-scope="scope">
              <span v-if="scope.row.active1">
                <el-input v-model="scope.row.remarks" @blur='onblurtives(scope.row)'></el-input>
              </span>
              <div v-else @click="onHidden(scope.row,'active1')"  style="cursor: pointer;">
                <span style=" display: inline-block;min-height:20px;">{{scope.row.remarks? scope.row.remarks :''}}</span>
              </div>
            </template>
          </el-table-column>
        </el-table>

      </div>
    </div>
    <!-- //批量修改 -->
    <el-dialog title="批量修改" :visible.sync="isVisible" width="375px" :before-close="handleClose" :close-on-click-modal="false">
      <div class="container-row">
        <el-form :model="form" ref="vForm" label-position="right" label-width="100px">
          <el-row>
            <el-col :span="24" class="grid-cell">
              <el-form-item label="已选择人数：" class="label-center-align">
                <span>{{multipleSelection.length}}人</span>
              </el-form-item>
              <el-form-item label="待修改属性：" class="label-center-align">
                <el-input v-model="form.values" placeholder="年终奖金额" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="待修改金额：" class="label-center-align">
                <el-input v-model="form.value"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisible = false">取 消</el-button>
        <el-button type="primary" @click="onmodificationamount">保存</el-button>
      </span>
    </el-dialog>

    <!-- //引入人员 -->
    <el-dialog title="同步人员" :visible.sync="isVisible1" width="60%" :before-close="handleClose1" :close-on-click-modal="false">
      <div class="container-row">
        <div class="block" style="margin-bottom:20px; display:flex;">
          <el-input v-model="form.query" placeholder="人员、工号" style="width:200px;"></el-input>
          <el-button type="primary" @click="serchUserlint">查询</el-button>
        </div>
        <div class="tableContens">
          <el-table :data="listArr" ref="Table" @selection-change="handleSelection" style="width: 100%" height="500px" class="pageInnerTable" :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column prop="jobno" label="工号" width="180">
            </el-table-column>
            <el-table-column prop="name" label="姓名" width="180">
            </el-table-column>
            <el-table-column prop="departmentName" label="部门">
            </el-table-column>
            <el-table-column prop="address" label="证照类型">
            </el-table-column>
            <el-table-column prop="idno" label="证照号码">
            </el-table-column>
          </el-table>
        </div>
        <div style="margin-top:10px;">
          <pagination @getTableData="getList" :total="total" :listQuery="listQuery" :pageSizes='pageSizes' />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="editUser">保存</el-button>
      </span>
    </el-dialog>
    <getimport :isDiaor='isDiaor' @handleClose='closeLIVE' :typestatus='1' :abId="params.abId" />
  </div>
</template>
<script>
import pagination from '@/components/pagination.vue';
import { getDepartmentView, Base64 } from '@/util/xc/utils';
import requestList from '@/api/moduleApi_xc/management';
import getimport from './components/getimport.vue';
export default {
  components: {
    pagination,
    getimport
  },
  name: "annualBonusDetail",
  data() {
    return {
      sDepartment: [], //部门
      mployeetype: [{ name: '全职', id: 1 }, { name: '兼职', id: 2 }],
      tableData: [],
      listArr: [],
      listQuery: {}, //分页
      isDiaor: false,
      total: 0,
      pageSizes: [50, 100, 200, 500],
      initobj: {
        id: '',
        userId: '',
        active: false,
        active1: false,
        annualBonus: 0,
        taxPayable: 0,
        sfAnnualBonus: 0,
        remarks: ""
      },
      isVisible: false, //dialog弹窗
      isVisible1: false, //引入人员
      multipleSelection: [], //选中人员
      multipleList: [],
      loading: false,
      loading1: false,
      form: {
        value: '',
        values: '',
        query: '',
      },
      PageIndex: 1,
      PageSize: 50,
      query: {
        year: '',
        subId: '',
      },
      params: {
        abId: 0,
        departmentid: '',
        noORname: '',
        postname: '',
        registertype: ""
      },
    };
  },
  watch: {
    $route: {
      handler(newval, oldval) {
        if(newval.meta.title == '编辑年终奖报表') {
          this.getinitData();
        }  
        //深度监听，同时也可监听到param参数变化
      },
      deep: true,
    }
  },
  created() {
    this.getinitData();
  },
  methods: {
    getinitData() {
      if (JSON.stringify(this.$route.query) != "{}") {
        let { subid, abid, year, status } = this.$route.query;
        this.query.subId = JSON.parse(Base64.decode(subid));
        this.params.abId = JSON.parse(Base64.decode(abid));
        this.query.year = JSON.parse(Base64.decode(year));
        if (status == 1) {
          //添加年终奖
          this.tableData = [];
        } else {
          //编辑年终奖
          this.editsave();
          
        }
        this.getCompany();
      }
    },
    // 初始化部门
    async getCompany() {
      this.sDepartment = [];
      this.params.departmentid = '';
      let { data } = await getDepartmentView(this.query.subId);
      this.sDepartment = data;
    },
    //搜索人员
    onserch() {
      this.editsave();
    },
    editsave() {
      //填写
      this.loading = true;
      let paramsLint = JSON.parse(JSON.stringify(this.params));
      Object.keys(paramsLint).forEach(item => {
        if (paramsLint[item] == "") {
          delete paramsLint[item];
        }
      });
      requestList.GeteditAnnualBonus(paramsLint).then(res => {
        let { data, status } = res.data;
        if (status == 200) {
          this.tableData = data.annualBonusItemViews;
          this.tableData.forEach(item => {
            console.log(item, 'item');
            item.active = false;
            item.active1 = false;
            item.annualBonus = item.annualBonusThs;
            item.sfAnnualBonus = item.sfAnnualBonusThs;
            item.taxPayable = item.taxPayableThs;
          });
          this.loading = false;
        } else {
          setTimeout(() => {
            this.loading = false;
          }, 3000);
        }
      }).catch(_ => {
        setTimeout(() => {
          this.loading = false;
        }, 3000);
      });

    },
    //引入人员
    cloneUser() {
      this.isVisible1 = true;
      this.listArr = [];
      this.serchUserlint();
    },
    serchUserlint() {
      let params = {
        abId: this.params.abId,
        query: this.form.query,
        PageIndex: this.PageIndex,
        PageSize: this.PageSize
      };
      if (params.query == "") {
        delete params.query;
      }
      requestList.GetuserListAnnualBonus(params).then(res => {
        let { data, status } = res.data;
        if (status == 200) {
          this.listArr = data['data'];
          this.total = data.total;
          console.log(res.data, 'this.listArr');
        }
      });
    },
    //分页搜索
    getList(e, status) {
      if (status == 'size') {
        this.PageSize = e;
      } else {
        this.PageIndex = e;
      }
      this.serchUserlint();
    },
    //确定引入
    editUser() {
      if (this.multipleList.length == 0) {
        this.$message({
          type: 'info',
          message: '你还没有选择要引入的人员',
        });
        return;
      }
      let userArr = this.multipleList.map(idx => idx.employeeid);
      requestList.GetuserDetailAnnualBonus({ abId: this.params.abId, userIds: userArr }).then(res => {
        let { status } = res.data;
        if (status == 200) {
          this.$message({
            type: 'success',
            message: '引入成功!'
          });
          this.handleClose1();
          this.onserch();
        }
      });
    },
    // 表格选中操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSelection(val) {
      this.multipleList = val;
    },
    closeLIVE(status) {
      this.isDiaor = false;
      if (status == '成功') {
        this.editsave();
      }
    },
    //批量修改金额
    onmodificationamount() {
      this.tableData.forEach(idx => {
        this.multipleSelection.forEach(idx1 => {
          if (idx.userId == idx1.userId) {
            idx.annualBonus = this.form.value;
            let rateMy = this.onCalculationrate(idx.annualBonus);
            idx.taxPayable = rateMy;
            idx.sfAnnualBonus = (idx.annualBonus - idx.taxPayable).toFixed(2);
          }
        });
      });
      this.handleClose();
    },
    //失去焦点
    onchangeput(row) {
      
      row.annualBonus = Number(row.annualBonus).toFixed(2);
    },
    onblurtive(row) {
      row.active = false;
      let rateMy = this.onCalculationrate(row.annualBonus);
      console.log(rateMy, 'rateMy');
      row.taxPayable = rateMy;
      row.sfAnnualBonus = (row.annualBonus - row.taxPayable).toFixed(2);
      this.$forceUpdate();
    },
    //失去焦点
    onblurtives(row) {
      row.active1 = false;
      this.$forceUpdate();
    },
    onHidden(row, status) {
      row[status] = true;
      this.$forceUpdate();
      console.log(row, 'row');
    },
    // *关闭批量修改弹窗回调
    handleClose() {
      this.isVisible = false;
    },
    // 关闭导入引入人员弹窗
    handleClose1() {
      this.isVisible1 = false;
    },
    // 导出操作
    exportget() {
      let paramsLint = { ...this.params };
      Object.keys(paramsLint).forEach(item => {
        if (paramsLint[item] == "") {
          delete paramsLint[item];
        }
      });
      requestList.expostAnnualBonus(paramsLint).then(res => {
        let { data, status } = res.data;
        if (status == 200) {
          window.open(data);
        }

      });
    },
    //打印
    onprint() {
      let paramsLint = { ...this.params };
      Object.keys(paramsLint).forEach(item => {
        if (paramsLint[item] == "") {
          delete paramsLint[item];
        }
      });
      requestList.PrintAnnualBonus(paramsLint).then(res => {
        let { data, status } = res.data;
        if (status == 200) {
          window.open(data);
        }
      });
    },

    //*批量修改
    onBulkchanges() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          type: 'info',
          message: '你还没有选择人员',
        });
        return;
      }
      this.form.value = "";
      this.isVisible = true;
    },
    //*批量删除
    ondelList() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          type: 'info',
          message: '你还没有选择人员',
        });
        return;
      }
      this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        let idsArr = this.multipleSelection.map(item => item.id);
        requestList.GetdelUserAnnualBonus({ ids: idsArr.join() }).then(res => {
          if (res.status == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.onserch();
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 计算税率
    onCalculationrate(money) {
      let rate = 0;
      if (money <= 36000) {
        rate = money * 0.03;
      } else if (money <= 144000) {
        rate = money * 0.1 - 2520;
      } else if (money <= 300000) {
        rate = money * 0.2 - 16920;
      } else if (money <= 420000) {
        rate = money * 0.25 - 31920;
      } else if (money <= 660000) {
        rate = money * 0.3 - 52920;
      } else if (money <= 960000) {
        rate = money * 0.35 - 85920;
      } else {
        rate = money * 0.45 - 181920;
      }
      return rate.toFixed(2);
    },
    inData() {
      const tableList = this.tableData;
      const addData = [];
      tableList.forEach(idx => {
        let obj = {};
        obj.id = idx.id;
        obj.userId = idx.userId;
        obj.annualBonus = Number(idx.annualBonus);
        obj.taxPayable = Number(idx.taxPayable);
        obj.sfAnnualBonus = Number(idx.sfAnnualBonus);
        obj.remarks = idx.remarks ? idx.remarks : '';
        addData.push(obj);
      });
     
      return addData;
    },
    //保存编辑
    onsaveAdd() {
      this.loading1 = true;
      console.log(this.inData());
      requestList.GetsaveDetailAnnualBonus({ abId: this.params.abId, annualBonusItemDtos: this.inData() }).then(res => {
        let { status } = res.data;
        if (status == 200) {
          this.$message({
            type: 'success',
            message: '保存成功!'
          });
          this.$bus.$emit('successchange', '成功');
          this.loading1 = false;
        } else {
          setTimeout(() => {
            this.loading1 = false;
          }, 3000);
        }
      }).catch(_ => {
        setTimeout(() => {
          this.loading1 = false;
        }, 3000);
      });
    }
  }
};
</script>
<style lang="less" scoped>
#annualBonusDetail {
  .pageHead {
    width: 100%;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    height: auto;
    .pageLf,
    .pageRg {
      display: flex;
      .block {
        margin-right: 5px;
       
      }
      .blocks{
        margin-left: -8px;
      }
    }
  }
  .container-row {
    padding: 20px 0px 20px 0px;
  }
  .pageBox {
    margin-top: 17px;
    width: 100%;
    height: calc(100% - 78px);
    float: left;
    position: relative;
    overflow: auto;
    .tableContens {
      height: calc(100% - 36px);
      position: relative;
      width: 100%;
      padding-right: 0;
    }
  }
}
</style>